class CustomersController < ApplicationController

  def autocomplete_by_key_words
    @customers = Customer.where(['key_words like ? ', "%#{params[:term]}%"]).active
  end

  def index
    if params[:tag_id].present?
      begin
        @tag = Tag.find(params[:tag_id])
        @customers = Customer.by_tag_id(params[:tag_id])
      rescue
        redirect_to :action => :index
      end
    elsif params[:untagged].present?
      @customers = Customer.untagged
    elsif params[:being_assinged].present?
      @customers = Customer.being_assinged
    elsif params[:filter].present?
      @customers = Customer.try(params[:filter])
    else  
      @customers = Customer.all
    end
  end

  def show
    @customer = Customer.find(params[:customer_id] || params[:id])
    BrowsedRecord.browses_it!(:customer_id => @customer.id)
  end

  def new
    @customer = Customer.new    
  end

  def create
    @customer = Customer.new params[:customer]
    if not @customer.save
      render :new 
    else
      redirect_to @customer
    end
  end

  def edit
    @customer = Customer.find(params[:id])
  end
  
  def update
    @customer = Customer.find(params[:id])
    if not @customer.update_attributes(params[:customer])
      render :edit 
    else
      redirect_to @customer
    end
  end
  
  def create_record
    @record = ContactRecord.new params[:contact_record]    
    render :new_record if not @record.save
  end
  
  def edit_record
    @record = ContactRecord.find(params[:id])
  end
  
  def update_record
    @record = ContactRecord.find(params[:id])
    if not @record.update_attributes(params[:contact_record])
      render :edit_record
    end
  end
  
  def destroy_record
    @record = ContactRecord.find(params[:id])
    @record.destroy
  end

  def blank_out_some
    @customers = Customer.find(params[:id]).each_with_object([]) do |customer,customers|
      customers << customer if customer.enterprise == Enterprise.current
    end
    @customers.each do |customer|
      customer.blank_out!
    end
  end

  def active_some
    @customers = Customer.find(params[:id]).each_with_object([]) do |customer,customers|
      customers << customer if customer.enterprise == Enterprise.current
    end
    @customers.each do |customer|
      customer.active!
    end
  end
end
